package ran.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import ran.constants.JwtCacheConstants;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-10-09
 * Time: 14:03
 */
public class JwtUtils {
    /**
     * 生成令牌
     *
     * @param claims 数据
     * @param secret 密钥
     * @return 令牌
     */
    public static String createToken(Map<String, Object> claims, String secret)
    {
        String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }
    /**
     * 从令牌中获取数据
     *
     * @param token 令牌
     * @param secret 密钥
     * @return 数据
     */
    public static Claims parseToken(String token, String secret) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    public static void main(String[] args) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId",123456);
        String secret = "dadddadadsetgsegsa";
        System.out.println(createToken(claims,secret));
        System.out.println(parseToken("eyJhbGciOiJIUzUxMiJ9.eyJ1c2VySWQiOjEyMzQ1Nn0.VwNV96RCS9Y-1_Bg8ak8xGPkaPdVPFdRBYDjCpjyqTMRHC1ZGRwxJZLENG7b44QhAWpA3wJZjzFvHn7R5QscAw",secret));
    }



    private static String toStr(Object val) {
        if (val == null) {
            return "";
        }
        return val.toString();
    }

    // 获取userId
    public static String getUserId(Claims claims) {
        return toStr(claims.get(JwtCacheConstants.LOGIN_USER_ID));
    }
    // 获取userKey
    public static String getUserKey(Claims claims) {
        return toStr(claims.get(JwtCacheConstants.LOGIN_USER_KEY));
    }
}
